package nio.tcp.server_client;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;

public class ServerSocketChannelTest {

    public static void main(String[] args) throws IOException {

        try (
                ServerSocketChannel channel = ServerSocketChannel.open();
                Selector selector = Selector.open();
        ) {

            channel.configureBlocking(false);
            channel.bind(new InetSocketAddress(Server.listener_port));
            channel.register(selector, SelectionKey.OP_ACCEPT);

            while (true) {
                SocketChannel client = channel.accept(); //非阻塞情况下，立即返回
                if (client != null) {
                    ByteBuffer bb = ByteBuffer.allocate(Server.buffer_size);
                    client.read(bb);
                    bb.flip();
                    System.out.println("来自客户端：" + Charset.forName("utf-8").newDecoder().decode(bb));
                    client.shutdownInput(); //关闭输入流

                    bb.clear();
                    bb.put("来自服务器的声音".getBytes());
                    bb.flip();
                    while (bb.hasRemaining()) {
                        client.write(bb);
                    }
                    client.shutdownOutput(); //关闭输出流
                }
            }
        }
    }
}
